package com.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

public class FileUtils extends org.apache.commons.io.FileUtils {

	public static String encodeFileName(HttpServletRequest req, String fileName)throws UnsupportedEncodingException {
		String agent = req.getHeader("USER-AGENT");
		if (null != agent && (-1 != agent.indexOf("MSIE") || -1 != agent.indexOf("Opera") || -1 != agent.indexOf("Chrome"))) {
			return URLEncoder.encode(fileName, "UTF8");
		} else if (null != agent && -1 != agent.indexOf("Safari")) {
			// Safari浏览器，只能采用ISO编码的中文输出
			return new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
		} else if (null != agent && -1 != agent.indexOf("Mozilla")) {
			// 其它浏览器如firefox等
			// return MimeUtility.encodeText(fileName, "UTF8", "B");
			// return "=?UTF-8?B?" + (new String
			// (BASE64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";

		} else {
			return fileName;
		}
		return fileName;
	}
	/**
	 * 移动或或复制文件
	 * @param moved 是否移动或重命名文件 
	 * @param replaced 当文件已存在时是否替换此文件
	 * @param srcFile 要移动或复制的源文件
	 * @param destFile 移动或复制的目的文件
	 * @return
	 * @throws IOException
	 */
	public static boolean renameTo(boolean moved,boolean replaced, File srcFile, File destFile) throws IOException {
		boolean flag = false;
		if (srcFile.getAbsolutePath().equalsIgnoreCase(destFile.getAbsolutePath())) {
			flag=false;
		} else {
			if(destFile.exists()){
				if( replaced ){
					destFile.delete();
					if (moved){
						flag = srcFile.renameTo(destFile);
					}else {
						copyFile(srcFile, destFile);
						flag=true;
					}
				}else{
					flag=false;
				}
			}else{
				if (moved){
					flag = srcFile.renameTo(destFile);
				}else {
					copyFile(srcFile, destFile);
					flag=true;
				}
			}
		}
		return flag;
	}

	public static void main(String[] args) throws IOException {
		File srcFile=new File("D:/test/src.txt");
		File destFile=new File("D:/test/新建文件夹/src.txt");
		System.out.println(renameTo(false,true, srcFile, destFile));;
	}
}
